/**
 *
 */
package com.yangtao.prototype.system.dao;

import com.yangtao.framework.common.Option;
import com.yangtao.framework.hibernate.BaseDao;
import com.yangtao.framework.hibernate.Selector;
import com.yangtao.prototype.common.tree.TreeResolver;
import com.yangtao.prototype.system.domain.Organization;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author 杨涛
 */
@Repository
public class OrganizationDao extends BaseDao<Organization> {

	/**
	 * 根据组织机构Id，取得组织机构的路径
	 *
	 * @param organizeId
	 * @return
	 */
	public String getOrganizePath(String organizeId) {
		Organization organization = load(organizeId);
		if (organization != null)
			return organization.getPath();
		return null;
	}

	/**
	 * 根据组织机构Id取得组织机构下所有的子机构
	 *
	 * @param organizationId 组织机构Id
	 * @return
	 */
	public List<Option> getSubOrganization(String organizationId) {
		String hql = "select new com.yangtao.framework.common.Option(organization.id,organization.name) " +
				"from Organization organization where organization.active = ?  ";
		Organization organization = load(organizationId);
		if (organization != null && StringUtils.isNotEmpty(organization.getPath())) {
			hql += " and organization.path like ? order by organization.level asc";
			return find(hql, true, organization.getPath() + "%");
		}
		hql += "order by organization.level asc";
		return find(hql, true);
	}

	/**
	 * 从特定节点下取得组织机构树
	 *
	 * @param organizationId 组织机构Id
	 * @return
	 */
	public List<Organization> getOrganizationStroe(String organizationId) {
		Selector selector = new Selector();
		String hql = "from Organization organization where organization.active = ? ";
		Organization organization = load(organizationId);
		if (organization != null && StringUtils.isNotEmpty(organization.getPath())) {
			hql += " and organization.path like ? ";
			List<Organization> organizations = find(selector, hql.toString(), true, organization.getPath() + "%");
			return TreeResolver.resolveTree(organizations, organization.parentId());
		}
		List<Organization> organizations = find(selector, hql.toString(), true);
		return TreeResolver.resolveTree(organizations);
	}

	/**
	 * 找到组织机构的根节点
	 *
	 * @return
	 */
	public Organization findRoot() {
		return findUnique("from Organization o where o.supOrganize.id is null");
	}
}
